<template>
  <div class="analysis-container">
    <el-row :gutter="20">
      <el-col :span="5">
        <el-card class="query-panel">
          <template #header>
            <div class="card-header">
              <span>查询条件</span>
            </div>
          </template>
          <el-form :model="queryForm" label-width="80px">
            <el-form-item label="布局方式">
              <el-select v-model="queryForm.layout" placeholder="请选择布局方式">
                <el-option label="地理布局" value="geographic" />
                <el-option label="层次布局" value="hierarchical" />
                <el-option label="辐射布局" value="radial" />
                <el-option label="力导向布局" value="force" />
              </el-select>
            </el-form-item>
            <el-form-item label="地区">
              <el-select v-model="queryForm.region" placeholder="请选择地区">
                <el-option label="全部" value="all" />
                <el-option label="台北地区" value="taipei" />
                <el-option label="台中地区" value="taichung" />
                <el-option label="台南地区" value="tainan" />
                <el-option label="花莲地区" value="hualien" />
                <el-option label="高雄地区" value="kaohsiung" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery" :loading="loading">查询</el-button>
              <el-button type="text" @click="resetHighlight" :disabled="!isHighlighted">重置高亮</el-button>
            </el-form-item>
          </el-form>
          
          <!-- 显示错误信息 -->
          <div v-if="error" class="error-message">
            <el-alert
              :title="error"
              type="error"
              show-icon
              :closable="true"
              @close="error = ''"
            />
          </div>
          
          <div v-if="tracedFacility" class="facility-detail">
            <div class="facility-title">
              <strong>{{ tracedFacility.name }}</strong>
              <el-tag :type="getTypeTag(tracedFacility.facility_type)" size="small">{{ getFacilityTypeName(tracedFacility.facility_type) }}</el-tag>
            </div>
            <div class="facility-info">
              <div class="info-item">
                <span class="label">储量/规模:</span>
                <span class="value">{{ tracedFacility.value }} 平方米</span>
              </div>
              <div class="info-item">
                <span class="label">区域:</span>
                <span class="value">{{ getRegionName(tracedFacility.region) }}</span>
              </div>
              <div class="info-item">
                <span class="label">连接数量:</span>
                <span class="value">{{ getConnectionCount(tracedFacility.id) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="19">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="map-container">
              <template #header>
                <div class="card-header">
                  <span>弹药设施分布图</span>
                  <div class="legend">
                    <div class="legend-item">
                      <span class="color-dot" style="background-color: #5E35B1;"></span>
                      <span>弹药制造厂</span>
                    </div>
                    <div class="legend-item">
                      <span class="color-dot" style="background-color: #D81B60;"></span>
                      <span>中央弹药库</span>
                    </div>
                    <div class="legend-item">
                      <span class="color-dot" style="background-color: #00897B;"></span>
                      <span>机场弹药库</span>
                    </div>
                    <div class="legend-item">
                      <span class="color-dot" style="background-color: #FFB300;"></span>
                      <span>军用机场</span>
                    </div>
                  </div>
                </div>
              </template>
              <div id="mapChart" class="chart" ref="mapChartRef"></div>
              <div v-if="loading" class="loading-overlay">
                <div class="spinner"></div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="12">
            <el-card class="network-container">
          <template #header>
            <div class="card-header">
                  <span>弹药供应网络关系图</span>
                  <div class="layout-switch">
                    <span class="layout-label">布局：{{ getLayoutName(queryForm.layout) }}</span>
                  </div>
            </div>
          </template>
              <div id="networkChart" class="chart" ref="networkChartRef"></div>
              <div v-if="loading" class="loading-overlay">
                <div class="spinner"></div>
              </div>
        </el-card>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import 'leaflet/dist/leaflet.css'
import L from 'leaflet'
import { getFacilities, getNetworkData, traceSupplyChain } from '@/api/ammunition-supply'

// 修复Leaflet图标在webpack中的问题
delete L.Icon.Default.prototype._getIconUrl
L.Icon.Default.mergeOptions({
  iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
  iconUrl: require('leaflet/dist/images/marker-icon.png'),
  shadowUrl: require('leaflet/dist/images/marker-shadow.png')
})

// 查询表单
const queryForm = ref({
  layout: 'force',
  region: 'all'
})

// 加载状态
const loading = ref(false)
// 错误状态
const error = ref('')

// 图表实例
let mapInstance = null
let markersLayer = null
let networkChart = null

// 数据
const networkData = ref({
  nodes: [],
  links: [],
  categories: []
})

// 追踪的设施
const tracedFacility = ref(null)

// 是否高亮状态
const isHighlighted = ref(false)

// 图表DOM引用
const mapChartRef = ref(null)
const networkChartRef = ref(null)

// 地区名称映射
const regionNames = {
  all: '全部',
  taipei: '台北地区',
  taichung: '台中地区',
  tainan: '台南地区',
  hualien: '花莲地区',
  kaohsiung: '高雄地区'
}

// 布局名称映射
const layoutNames = {
  geographic: '地理布局',
  hierarchical: '层次布局',
  radial: '辐射布局',
  force: '力导向布局'
}

// 获取布局名称
const getLayoutName = (layout) => {
  return layoutNames[layout] || layout
}

// 获取区域名称
const getRegionName = (region) => {
  return regionNames[region] || region
}

// 获取设施类型的颜色
const getFacilityTypeColor = (facilityType) => {
  const colors = {
    'production': '#5E35B1',  // 紫色 - 弹药制造厂
    'central': '#D81B60',     // 红色 - 中央弹药库
    'airport_depot': '#00897B', // 绿色 - 机场弹药库
    'standard': '#00897B',    // 绿色 - 标准弹药库
    'special': '#00897B',     // 绿色 - 特种弹药库
    'airport': '#FFB300'      // 橙色 - 军用机场
  }
  return colors[facilityType] || '#9E9E9E' // 默认灰色
}

// 获取设施类型名称
const getFacilityTypeName = (facilityType) => {
  const typeNames = {
    'production': '弹药制造厂',
    'central': '中央弹药库',
    'airport_depot': '机场弹药库',
    'standard': '标准弹药库',
    'special': '特种弹药库',
    'airport': '军用机场'
  }
  return typeNames[facilityType] || facilityType
}

// 获取设施类型对应的标签类型
const getTypeTag = (facilityType) => {
  const tagTypes = {
    'production': 'primary', 
    'central': 'danger',
    'airport_depot': 'success',
    'standard': 'success',
    'special': 'warning',
    'airport': 'info'
  }
  return tagTypes[facilityType] || 'info'
}

// 获取连接数量
const getConnectionCount = (facilityId) => {
  if (!networkData.value || !networkData.value.links) {
    return 0
  }
  
  return networkData.value.links.filter(link => 
    link.source === facilityId || 
    link.target === facilityId ||
    (link.source && link.source.id === facilityId) || 
    (link.target && link.target.id === facilityId)
  ).length
}

// 获取节点名称（用于连接提示）
const getNodeName = (node) => {
  if (typeof node === 'object') {
    return node.name
  }
  const foundNode = networkData.value?.nodes?.find(n => n.id === node)
  return foundNode ? foundNode.name : `节点${node}`
}

// 加载初始数据
const loadInitialData = async () => {
  // 直接加载网络数据
  await loadNetworkData()
}

const handleQuery = async () => {
  await loadNetworkData()
}

// 获取网络数据
const loadNetworkData = async () => {
  loading.value = true
  error.value = ''
  
  try {
    console.log('Loading ammunition network data with params:', { region: queryForm.value.region })
    // 修改为使用导入的API函数
    const response = await getNetworkData({ region: queryForm.value.region })
    console.log('Ammunition network data response:', response)
    
    // 处理响应数据 - Axios 会将响应包装在 data 属性中
    const data = response.data || response
    
    // 验证数据格式
    if (!data || !Array.isArray(data.nodes) || !Array.isArray(data.links)) {
      throw new Error('无效的弹药网络数据格式')
    }
    
    // 更新网络数据
    networkData.value = data
    
    // 如果没有数据，显示提示
    if (data.nodes.length === 0) {
      ElMessage.warning('未找到任何弹药设施数据')
    } else {
      // 更新图表
      await nextTick()
      // 确保图表实例初始化
      if (!mapInstance) {
        initMap()
      }
      if (!networkChart) {
        initNetworkChart()
      }
      
      // 更新地图标记和网络图
      updateMapMarkers(networkData.value.nodes)
      updateNetworkChart(networkData.value)
      
      ElMessage({
        message: `成功加载了 ${networkData.value.nodes.length} 个设施和 ${networkData.value.links.length} 条连接`,
        type: 'success'
      })
    }
  } catch (err) {
    console.error('加载弹药网络数据失败:', err)
    error.value = `加载弹药网络数据失败: ${err.message || '未知错误'}`
    ElMessage.error('无法加载弹药供应网络数据')
  } finally {
    loading.value = false
  }
}

// 追踪设施供应链函数修改
const highlightFacility = async (facilityId) => {
  if (!facilityId) {
    error.value = '未指定设施ID'
    return
  }
  
  if (loading.value) {
    return
  }
  
  loading.value = true
  error.value = ''
  
  try {
    console.log(`请求追踪弹药设施供应链，原始ID: ${facilityId}, 类型: ${typeof facilityId}`)
    
    // 确保ID是正确的格式
    let traceId = facilityId;
    
    // 如果ID是对象，提取id属性
    if (typeof facilityId === 'object' && facilityId.id) {
      traceId = facilityId.id;
      console.log(`ID是对象，提取id属性: ${traceId}`);
    }
    
    // 如果ID以"airport_"开头，表示这是一个机场ID，不应该追踪
    if (typeof traceId === 'string' && traceId.startsWith('airport_')) {
      throw new Error('无法追踪机场节点，请选择弹药设施节点');
    }
    
    // 使用导入的API函数
    const response = await traceSupplyChain(traceId)
    console.log('追踪响应:', response)
    
    // 处理响应数据 - Axios 会将响应包装在 data 属性中
    const traceData = response.data || response
    
    // 验证数据格式
    if (!traceData || !Array.isArray(traceData.nodes) || !Array.isArray(traceData.links)) {
      throw new Error('无效的追踪数据格式')
    }
    
    if (!traceData.facility) {
      throw new Error(`未找到ID为${traceId}的设施`)
    }
    
    // 设置当前追踪的设施
    tracedFacility.value = traceData.facility
    
    // 获取节点ID列表
    const highlightedNodeIds = traceData.nodes.map(node => node.id)
    console.log('高亮的节点IDs:', highlightedNodeIds)
    
    // 更新网络图和地图标记的高亮状态
    updateNetworkChart(networkData.value, highlightedNodeIds)
    updateMapMarkers(networkData.value.nodes, highlightedNodeIds)
    
    // 设置高亮状态
    isHighlighted.value = true
    
    ElMessage({
      message: `成功追踪设施 ${traceData.facility.name} 的供应链关系`,
      type: 'success'
    })
  } catch (err) {
    console.error('追踪设施供应链失败:', err)
    error.value = `追踪设施供应链失败: ${err.message || '未知错误'}`
    ElMessage.error(`无法完成设施追踪: ${err.message || '未知错误'}`)
  } finally {
    loading.value = false
  }
}

// 重置高亮
const resetHighlight = () => {
  try {
    // 重置追踪的设施
    tracedFacility.value = null
    
    // 重置网络图高亮
    if (networkChart) {
      updateNetworkChart(networkData.value)
    }
    
    // 清除地图标记层上的高亮
    if (mapInstance && markersLayer) {
      updateMapMarkers(networkData.value.nodes)
    }
    
    // 重置高亮状态
    isHighlighted.value = false
    
    // 清除错误消息
    error.value = ''
    
    ElMessage({
      message: '已重置所有高亮',
      type: 'success'
    })
  } catch (err) {
    console.error('重置高亮时出错:', err)
    error.value = `重置高亮时出错: ${err.message || '未知错误'}`
    ElMessage.error('重置高亮时出错')
  }
}

// 窗口调整处理
const handleWindowResize = () => {
  try {
    // 调整地图大小
    if (mapInstance) {
      mapInstance.invalidateSize()
    }
    
    // 调整网络图大小
    if (networkChart) {
      networkChart.resize()
    }
  } catch (err) {
    console.error('窗口大小调整时出错:', err)
  }
}

// 生命周期钩子
onMounted(async () => {
  try {
    console.log('组件已挂载，开始初始化...')
    
    // 初始化窗口调整事件
    window.addEventListener('resize', handleWindowResize)
    
    // 先初始化图表实例
    await nextTick()
    initMap()
    initNetworkChart()
    
    // 再加载网络数据
    await loadNetworkData()
    
    console.log('组件初始化完成')
  } catch (err) {
    console.error('组件初始化失败:', err)
    error.value = `组件初始化失败: ${err.message || '未知错误'}`
    ElMessage.error('应用初始化失败')
  }
})

// 组件卸载时清理
onUnmounted(() => {
  // 移除窗口调整事件
  window.removeEventListener('resize', handleWindowResize)
  
  // 销毁地图实例
  if (mapInstance) {
    mapInstance.remove()
    mapInstance = null
  }
  
  // 销毁图表实例
  if (networkChart) {
    networkChart.dispose()
    networkChart = null
  }
})

// 监听布局变化
watch(() => queryForm.value.layout, () => {
  if (networkChart && networkData.value) {
  networkChart.setOption({
      series: [{
        name: '弹药供应',
        layout: queryForm.value.layout
      }]
    })
  }
})

// 添加缺失的地图初始化函数
const initMap = () => {
  try {
    // 确保mapChartRef已经挂载
    if (!mapChartRef.value) {
      console.error('地图容器未挂载')
      return
    }
    
    console.log('初始化地图...')
    
    // 如果已存在地图实例，先清除
    if (mapInstance) {
      mapInstance.remove()
    }
    
    // 初始化地图实例
    mapInstance = L.map('mapChart', {
      center: [23.7, 121.0],  // 台湾中心位置
      zoom: 7,
      zoomControl: true,
      scaleControl: true,
      minZoom: 8,
      maxZoom: 11,
      maxBounds: L.latLngBounds(
        L.latLng(22.0, 119.8),  // 西南角
        L.latLng(25.4, 122.0)   // 东北角
      )
    })
    
    // 使用离线地图数据
    const offlineLayer = L.tileLayer('/assets/map-of-taiwan/gaode_map/{z}/{x}/{y}.png', {
      minZoom: 8,
      maxZoom: 11,
      tileSize: 256,
      attribution: '高德地图离线数据',
      errorTileUrl: '',
      noWrap: true,
      bounds: L.latLngBounds(
        L.latLng(20.63278, 119.53125),  // 西南角
        L.latLng(25.79989, 122.34375)   // 东北角
      ),
      tms: false,
      crossOrigin: true,
      subdomains: '',
      detectRetina: false
    })
    
    // 添加图层
    offlineLayer.addTo(mapInstance)
    
    // 创建标记图层
    markersLayer = L.layerGroup().addTo(mapInstance)
    
    console.log('地图初始化完成')
  } catch (err) {
    console.error('初始化地图失败:', err)
    error.value = `初始化地图失败: ${err.message || '未知错误'}`
  }
}

// 添加缺失的地图标记更新函数
const updateMapMarkers = (nodes, highlightedIds = []) => {
  try {
    if (!mapInstance || !markersLayer) {
      console.error('地图或标记图层未初始化')
      return
    }
    
    console.log('更新地图标记...')
    
    // 清除现有标记
    markersLayer.clearLayers()
    
    // 标记是否处于高亮状态
    const isHighlighting = highlightedIds && highlightedIds.length > 0
    
    // 添加新标记
    nodes.forEach(node => {
      if (!node.latitude || !node.longitude) {
        return // 跳过没有坐标的节点
      }
      
      // 检查是否高亮
      const isHighlighted = !isHighlighting || highlightedIds.includes(node.id)
      
      // 创建图标样式
      const markerIcon = L.divIcon({
        className: 'custom-div-icon',
        html: `<div style="
          background-color: ${getFacilityTypeColor(node.facility_type)};
          opacity: ${isHighlighted ? 1 : 0.3};
          border: 2px solid white;
          border-radius: 50%;
          width: ${20 + Math.min(node.value / 20, 30)}px;
          height: ${20 + Math.min(node.value / 20, 30)}px;
        "></div>`,
        iconSize: [30, 30],
        iconAnchor: [15, 15]
      })
      
      // 创建标记
      const marker = L.marker([node.latitude, node.longitude], { icon: markerIcon })
        .addTo(markersLayer)
      
      // 添加弹出窗口
      marker.bindPopup(`
        <div class="facility-popup">
          <div><strong>${node.name}</strong></div>
          <div>类型: ${getFacilityTypeName(node.facility_type)}</div>
          <div>区域: ${getRegionName(node.region)}</div>
          <div>面积: ${node.value} 平方米</div>
        </div>
      `)
      
      // 添加点击事件
      marker.on('click', () => {
        // 只对弹药库节点进行追踪，不对机场节点追踪
        if (node.facility_type !== 'airport') {
          console.log('追踪弹药库节点:', node.id, node.name, node.facility_type)
          highlightFacility(node.id)
        } else {
          console.log('点击了机场节点，不执行追踪:', node.id, node.name)
        }
      })
    })
    
    console.log('地图标记更新完成')
  } catch (err) {
    console.error('更新地图标记失败:', err)
    error.value = `更新地图标记失败: ${err.message || '未知错误'}`
  }
}

// 添加网络图表初始化函数
const initNetworkChart = () => {
  try {
    // 确保网络图表容器已挂载
    if (!networkChartRef.value) {
      console.error('网络图表容器未挂载')
      return
    }
    
    console.log('初始化网络图表...')
    
    // 初始化网络图表实例
    networkChart = echarts.init(document.getElementById('networkChart'))
    
    // 配置基本选项
    const option = {
    tooltip: {
      trigger: 'item',
        formatter: function(params) {
          if (params.dataType === 'node') {
            return `
              <div style="font-weight:bold">${params.data.name}</div>
              <div>类型: ${getFacilityTypeName(params.data.facility_type || 'unknown')}</div>
              <div>区域: ${getRegionName(params.data.region || 'unknown')}</div>
              <div>面积: ${params.data.value || 0} 平方米</div>
            `
          } else {
            return `从 ${getNodeName(params.data.source)} 到 ${getNodeName(params.data.target)}`
          }
        }
    },
    legend: {
        show: true,
        data: ['弹药制造厂', '中央弹药库', '机场弹药库', '军用机场'],
        bottom: 10,
        left: 'center'
    },
    series: [{
      type: 'graph',
      layout: queryForm.value.layout,
      roam: true,
        label: {
          show: true,
          position: 'right'
        },
        edgeSymbol: ['circle', 'arrow'],
        edgeSymbolSize: [4, 8],
        data: [],
        links: [],
        categories: [
          { name: '弹药制造厂' },
          { name: '中央弹药库' },
          { name: '机场弹药库' },
          { name: '军用机场' }
        ],
        emphasis: {
          focus: 'adjacency'
        }
      }]
    }
    
    // 应用配置
    networkChart.setOption(option)
    
    // 添加点击事件
    networkChart.on('click', (params) => {
      if (params.dataType === 'node') {
        // 只对弹药库节点进行追踪，不对机场节点追踪
        if (params.data.facility_type !== 'airport') {
          console.log('追踪弹药库节点:', params.data.id, params.data.name, params.data.facility_type)
          highlightFacility(params.data.id)
        } else {
          console.log('点击了机场节点，不执行追踪:', params.data.id, params.data.name)
        }
      }
    })
    
    console.log('网络图表初始化完成')
  } catch (err) {
    console.error('初始化网络图表失败:', err)
    error.value = `初始化网络图表失败: ${err.message || '未知错误'}`
  }
}

// 更新网络图表
const updateNetworkChart = (data, highlightedIds = []) => {
  try {
    if (!networkChart) {
      console.error('网络图表实例不存在')
      return
    }
    
    if (!data || !data.nodes || !data.links) {
      console.error('无效的网络数据')
      return
    }
    
    console.log('正在更新网络图...')
    
    // 是否处于高亮状态
    const isHighlighting = highlightedIds && highlightedIds.length > 0
    
    // 节点数据处理
    const nodes = data.nodes.map(node => {
      // 高亮状态处理
      const isHighlighted = !isHighlighting || highlightedIds.includes(node.id)
      const opacity = isHighlighted ? 1 : 0.3
      
      // 确保节点有所有必要属性
      return {
        ...node,
        itemStyle: {
          color: getFacilityTypeColor(node.facility_type),
          opacity: opacity,
          borderWidth: 2,
          borderColor: '#fff'
        },
      label: {
        show: true,
        position: 'right',
          formatter: '{b}',
          fontSize: 12,
          color: '#303133'
      },
        symbolSize: node.symbolSize || (20 + Math.min(node.value / 10, 30)),
      emphasis: {
          scale: true,
          label: {
            show: true,
            fontWeight: 'bold',
            fontSize: 14
          }
        }
      }
    })
    
    // 连接数据处理
    const links = data.links.map(link => {
      let isHighlighted = false
      
      // 如果有高亮节点，检查连接是否连接到高亮节点
      if (isHighlighting) {
        const sourceId = typeof link.source === 'object' ? link.source.id : link.source
        const targetId = typeof link.target === 'object' ? link.target.id : link.target
        isHighlighted = highlightedIds.includes(sourceId) && highlightedIds.includes(targetId)
      } else {
        isHighlighted = true
      }
      
      return {
        ...link,
        symbolSize: [5, 8],
        lineStyle: {
          width: isHighlighted ? 3 : 1,
          opacity: isHighlighted ? 0.9 : 0.3,
          color: isHighlighted ? '#409EFF' : '#bbb',
          curveness: 0.2,
          type: 'solid'
        },
        label: {
          show: false
        },
        emphasis: {
          lineStyle: {
            width: 4,
            color: '#409EFF'
          }
        }
      }
    })
    
    // 更新图表配置
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          if (params.dataType === 'node') {
            return `
              <div style="font-weight:bold">${params.data.name}</div>
              <div>类型: ${getFacilityTypeName(params.data.facility_type)}</div>
              <div>区域: ${getRegionName(params.data.region)}</div>
              <div>面积: ${params.data.value} 平方米</div>
            `
          } else {
            return `从 ${getNodeName(params.data.source)} 到 ${getNodeName(params.data.target)}`
          }
        }
      },
      legend: {
        show: true,
        data: ['弹药制造厂', '中央弹药库', '机场弹药库', '军用机场'],
        bottom: 10,
        left: 'center',
        selectedMode: false,
        textStyle: {
          fontSize: 12
        }
      },
      animationDurationUpdate: 1500,
      animationEasingUpdate: 'quinticInOut',
      series: [{
        type: 'graph',
        layout: queryForm.value.layout,
      force: {
          repulsion: 1500,
          gravity: 0.1,
          edgeLength: [100, 300],
          layoutAnimation: true
        },
        roam: true,
        draggable: true,
        zoom: 1,
        center: ['50%', '50%'],
        symbol: 'circle',
        data: nodes,
        links: links,
        categories: data.categories || [
          { name: '弹药制造厂' },
          { name: '中央弹药库' },
          { name: '机场弹药库' },
          { name: '军用机场' }
        ],
        emphasis: {
          focus: 'adjacency',
          scale: true
        },
        edgeSymbol: ['circle', 'arrow'],
        edgeSymbolSize: [4, 8],
        lineStyle: {
          color: '#bbb',
          curveness: 0.2,
          width: 2
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{b}',
          fontSize: 12
        }
      }]
    }
    
    // 如果是地理布局模式，添加经纬度映射
    if (queryForm.value.layout === 'geographic') {
      nodes.forEach(node => {
        if (node.latitude !== undefined && node.longitude !== undefined) {
          node.x = node.longitude
          node.y = node.latitude
        } else if (node.lat !== undefined && node.lng !== undefined) {
          node.x = node.lng
          node.y = node.lat
        }
      })
    }
    
    // 应用配置更新
    networkChart.setOption(option, true)
    
    console.log('网络图更新成功')
  } catch (err) {
    console.error('更新网络图表失败:', err)
    error.value = `更新网络图表失败: ${err.message || '未知错误'}`
  }
}
</script>

<style scoped>
.analysis-container {
  padding: 20px;
  height: 100vh;
  overflow: hidden;
}

.query-panel {
  height: calc(100vh - 40px);
  overflow-y: auto;
}

.map-container, .network-container {
  height: calc(100vh - 40px);
}

.chart {
  width: 100%;
  height: calc(100% - 60px);
}

#mapChart, #networkChart {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.legend {
  display: flex;
  gap: 15px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.color-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 5px;
}

.facility-detail {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.facility-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.facility-info {
  font-size: 14px;
}

.info-item {
  display: flex;
  margin-bottom: 5px;
}

.label {
  width: 90px;
  color: #606266;
}

.value {
  flex: 1;
  color: #303133;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 123, 255, 0.2);
  border-radius: 50%;
  border-top-color: #007bff;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.layout-switch {
  display: flex;
  align-items: center;
}

.layout-label {
  margin-right: 10px;
  font-size: 13px;
  color: #606266;
}

:deep(.el-card__body) {
  position: relative;
  padding: 15px;
}

:deep(.facility-tooltip) {
  font-size: 12px;
  padding: 5px 8px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  border-radius: 4px;
}

/* 添加错误消息样式 */
.error-message {
  margin: 10px 0;
}

.error-message .el-alert {
  margin-bottom: 10px;
}
</style> 